var express = require('express');
var multer=require('multer')
var fs=require('fs')

var router = express.Router();
var avoidTheLogin = ['/login'];

router.use(function (req, res, next) {
    var token = req.headers.token || ''
    console.info(token)
    if(avoidTheLogin.indexOf(req.url) === -1 && token !== '123'){
        res.status(401).send({
            code: '001',
            data: {},
            msg: '登录过期'
        });
        return
    }

    next()
})

/* GET home page. */
router.get('/', function(req, res, next) {
    console.info('请求进来了')
    res.send({a:1});
});


router.post('/login', function(req, res, next) {
    var phone = req.body.phone
    var password = req.body.password
    var result;
    console.info(phone, password)
    if(phone === '18166956118' && password === '123123'){
        result = {
            code: '000',
            data: {
                userId: 1,
                token: '123',
                phone: phone,
                userName: '黄'
            },
            msg: '登录成功'
        }
    }else {
        result = {
            code: '901',
            data: {},
            msg: '账号或密码错误'
        }
    }
    res.send(result);
});

router.get('/getUserInfo', function(req, res, next) {
    res.send({
        code: '000',
        data: {
            userId: 1,
            phone: '18166956118',
            userName: '黄'
        },
        msg: '账号或密码错误'
    });
});

router.get('/geta', function(req, res, next) {
    res.status(401).send({
        code: '001',
        data: {},
        msg: '登录过期'
    });
});

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/temporaryDocuments');
    },
    //给上传文件重命名，获取添加后缀名
    filename: function (req, file, cb) {
        var suffixname  = file.originalname.split('.')
        cb(null, Date.now() +'.'+ suffixname[suffixname.length-1]);
    }
});
//添加配置文件到muler对象。
var upload = multer({
    storage: storage
}).array('photos[]', 9);

router.post('/diarize' , function(req, res, next) {
    console.info('---req.body--')
    upload(req, res, function (err) {
        console.info(req.body)
        if (err instanceof multer.MulterError) {
            // 发生错误
        } else if (err) {
            // 发生错误
        }
        res.send({
            code: '001',
            data: {},
            msg: '登录过期'
        });
    })
});


module.exports = router;
